import React, { Component } from 'react'
import { NavBar, Icon, Tabs, Toast } from 'antd-mobile';
import SearchInput from "../searchinput/SearchInput"
import "./GoodList.scss"
import myaxios from "../../utils/myaxios.js"
import EmtpyImg from "../../assest/empty_product.jpg"

export default class GoodList extends Component {
  constructor(props) {
    super(props);
    // 列表的引用
    this.goodListRef = React.createRef();
    this.pagesize = 20;//默认返回的每次请求数量
    this.pagenum = 1;//默认返回的每次请求数量
  }

  state = {
    tabs: [
      { title: "综合" }, { title: "销量" }, { title: "价格" }
    ],
    goods: []
  }
  componentDidMount() {
    let { search } = this.props.location;
    let params = search.split("?")[1] || ""
    let params_str = params.split("=");
    if (params_str[0] === "cid") {
      this.cid = params_str[1]
    } else if (params_str[0] === "query") {
      this.query = params_str[1];
    }
    this.getProductList();
    // 注册滚动监听事件
    console.log(this.goodListRef)
    this.goodListRef.current.parentElement.addEventListener("scroll", this.handleScroll)
  }
  handleScroll = () => {
    // console.log("列表开始滚动")
    let parentElement = this.goodListRef.current.parentElement;
    // 客户端高度
    let clientHeight = parentElement.clientHeight
    // console.log("列表高度" + clientHeight)
    // 列表高度
    let scrollHeight = parentElement.scrollHeight
    // console.log("列表高度", scrollHeight)
    // 列表已经滚动的高度
    let scrollTop = parentElement.scrollTop
    // console.log("列表已经滚动的高度" + scrollTop)
    // 如果结果小于或等于0，已经触底
    // console.log(scrollHeight - clientHeight - scrollTop)
    // 发请求获取最新数据
    if (scrollHeight - clientHeight - scrollTop <= 0) {
      console.log("触底啦")
      this.getProductList();
    }
  }
  componentWillUnmount() {
    // 卸载监听事件
    this.goodListRef.current.parentElement.removeEventListener("scroll", this.handleScroll)
  }
  // 获取数据列表
  getProductList = () => {
    // this.total null
    // this.pagesize null

    // 拼接参数
    let params = {}
    if (this.cid) {
      params["cid"] = this.cid
    }
    if (this.query) {
      params["query"] = decodeURIComponent(this.query)
    }

    // 如果页码存在
    if(this.total){
      params["pagenum"] = ++this.pagenum;
    }else{
      params["pagenum"]=this.pagenum
    }
   
    // 如果当前页码大于总页码不用发送请求
    if (this.pagenum && this.pagenum> Math.ceil(this.total / this.pagesize)) {
      Toast.info("产品已经全部加载完毕")
    } else {

      myaxios.get("goods/search", {
        params: params
      }).then((res) => {
        this.total = res.total;
        this.pagenum = res.pagenum;
        this.setState({
          goods: [...this.state.goods, ...res.goods]//追加数据

        })
      }).catch(err => console.log(err))
    }
  }

  handleItemClick = (goods_id) => {
    this.props.history.push("/goodDetail/" + goods_id)
  }


  render() {
    return (
      <div className="yg-goodList">
        {/* 分类页面导航开始 */}
        <div className="yg-gl-nav"><NavBar className="gl-nav" icon={<Icon type="left" />}
          onLeftClick={() => window.history.go(-1)}>商品列表</NavBar></div>
        {/* 分类页面导航结束 */}
        {/* 分类页面搜索开始 */}
        <div className="yg-gl-search"> <SearchInput></SearchInput></div>
        {/* 分类页面搜索框结束 */}

        {/* tab开始 */}
        <div className="yg-tab">
          <Tabs tabs={this.state.tabs}
            initialPage={0}
            onChange={(tab, index) => { console.log('onChange', index, tab); }}
            onTabClick={(tab, index) => { console.log('onTabClick', index, tab); }}
            tabBarUnderlineStyle={{ borderColor: "red" }}
            tabBarTextStyle={{ color: "black" }}>
            <div className="yg-goodlist-zh" ref={this.goodListRef}>
              {this.state.goods.map((val, index) => {
                return (
                  <div className="Tab-zh-item" key={val.goods_id} onClick={this.handleItemClick.bind(this, val.goods_id)}>
                    <div className="zh-item-left">
                      <img src={val.goods_small_logo ? val.goods_small_logo : EmtpyImg} alt="" />
                    </div>
                    <div className="zh-item-right">
                      <div className="item-right-top">{val.goods_name}</div>
                      <div className="item-right-bottom">￥{val.goods_price}</div>
                    </div>
                  </div>
                )
              })}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '150px', backgroundColor: '#fff' }}>
              销量
            </div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '150px', backgroundColor: '#fff' }}>
              价格
            </div>
          </Tabs>
        </div>
        {/* tab结束 */}
      </div>
    )
  }
}
